package com.zhanggm.springcloud.student.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/student/")
public class UploadController {

    @Value("${file.path}")
    private String filePath;

    @Value("${file.domain}")
    private String fileDomain;

    @RequestMapping("upload")
    public Object upload(@RequestParam("file") MultipartFile file){
        //文件名称
        String originalFilename = file.getOriginalFilename();
        String extFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+extFileName;
        String fileFullName = filePath+fileName;
        //保存文件
        File saveFile = new File(fileFullName);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回结果
        Map<String,Object> result = new HashMap<>();
        result.put("fileName",fileName);
        result.put("imgUrl",fileDomain+fileName);
        return result;
    }
}
